/******************************************************************************
 * Copyright (C) 2016 Wuhan Water Elephant Co.Ltd All Rights Reserved. 
 * 本软件为武汉水象科技有限公司开发研制。 未经本公司正式书面同意，其他任何个人、
 * 团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package com.loanapp.server.market.provider.modular.customer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.loanapp.base.common.exception.BusinessException;
import com.loanapp.base.common.utils.DoubleUtil;
import com.loanapp.base.common.utils.StringUtil;
import com.loanapp.base.database.common.base.SqlMapper;
import com.loanapp.server.market.api.customer.entity.CustomerBorrowInfo;
import com.loanapp.server.market.api.customer.query.CustomerBorrowInfoQuery;
import com.loanapp.server.market.provider.modular.customer.mapper.CustomerBorrowInfoMapper;
import com.loanapp.server.market.provider.modular.customer.service.CustomerBorrowInfoService;
import com.loanapp.server.market.provider.modular.platform.service.PlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerBorrowInfoServiceImpl  implements CustomerBorrowInfoService {

    @Autowired
    private CustomerBorrowInfoMapper mapper;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    private PlatformService platformService;

    @Override
    public PageInfo<Map<String, Object>> getBorrowInfoListPage(CustomerBorrowInfoQuery query, int[] pageParams) throws Exception {
        PageHelper.startPage(pageParams[0],pageParams[1]);
        Map<String,Object> params=new HashMap<>();
        String sql="SELECT a.id,b.product_name productName,c.logo,b.min_quato,b.max_quato," +
                "b.min_cycle,b.max_cycle,b.daily_interest_rate dailyInterestRate,b.lend_speed lendSpeed,a.product_id productId"+
                " FROM customer_borrow_info a JOIN platform_product_info b ON a.product_id = b.id JOIN platform_company_info c ON b.company_id=c.id where 1=1";
       if(query!=null){
          if(StringUtil.isNotEmpty(query.getBorrowerId())){
              sql+=" and a.borrower_id=#{borrowerId}";
             params.put("borrowerId",query.getBorrowerId());
          }
       }
       sql+=" order by a.create_time desc";
        List<Map<String, Object>> list =sqlMapper.selectList(sql,params);
        PageInfo pageInfo = new PageInfo(list);
        for (Map<String, Object> map : list) {
            map.put("productId", StringUtil.toString(map.get("productId")));// 产品ID
            map.put("productName", StringUtil.toString(map.get("productName")));// 公司名称
            map.put("logo", StringUtil.toString(map.get("logo")));// logo
            map.put("lendSpeed", StringUtil.toString(map.get("lendSpeed")));//  放款速度
            map.put("dailyInterestRate", StringUtil.toString(map.get("dailyInterestRate")));// 日利息
            map.put("quato",
                    getQuato(StringUtil.toString(map.get("min_quato")), StringUtil.toString(map.get("max_quato"))));// 放款额度
            map.put("cycle",
                    getCycle((int)map.get("min_cycle"),(int)map.get("max_cycle")) + "天");// 期限范围
            // 查询标签
            map.remove("min_cycle");
            map.remove("max_cycle");
            map.remove("min_quato");
            map.remove("max_quato");
            String label = platformService.getPlatformLabel(StringUtil.toString(map.get("productId")));
            map.put("label", label);// 标签
        }
        return  pageInfo;
    }


    private String getQuato(String minQuato, String maxQuato) {
        String quato = "";
        if (!StringUtil.isEmpty(minQuato)) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato));
        }
        if (!StringUtil.isEmpty(maxQuato)&&!maxQuato.equals("0.00")) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
        }
        if (!StringUtil.isEmpty(minQuato) && !StringUtil.isEmpty(maxQuato)&&!maxQuato.equals("0.00")) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato)) + "~"
                    + DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
        }
        return quato;
    }

    private String getCycle(Integer minCycle, Integer maxCycle) {
        String Cycle = "";
        if (minCycle!=null) {
            Cycle+= minCycle;
        }
        if (maxCycle!=null) {
            Cycle+=maxCycle;
        }
        if (minCycle!=null&&maxCycle!=null) {
            Cycle = minCycle + "~"
                    + maxCycle;
        }
        return Cycle;
    }

    @Override
    public List<Map<String, Object>> getApplyListPage(int[] page, Long user) {
        StringBuilder sql = new StringBuilder();
        int pageNo = page[0];
        int pageSize = page[1];
        sql.append("SELECT ");
        sql.append("a.id, ");
        sql.append("arg0.id as productId, ");
        sql.append("arg0.product_img as productLogo, ");
        sql.append("arg0.product_name as productName, ");
        sql.append("arg0.min_quato, ");
        sql.append("arg0.max_quato, ");
        sql.append("arg0.lend_speed as lendSpeed, ");
        sql.append("arg0.min_cycle, ");
        sql.append("arg0.max_cycle, ");
        sql.append("FORMAT(IFNULL(arg0.daily_interest_rate,0)*30,2) as dailyInterestRate ");
        sql.append("FROM customer_application_record a ");
        sql.append("LEFT JOIN platform_product_info arg0 ON arg0.id = a.product_id ");
        sql.append("WHERE 1=1 ");
        sql.append("AND arg0.`status` = 1 ");
        sql.append("AND a.borrower_id = '" + user + "' ");
        sql.append("ORDER BY a.create_time DESC ");
        sql.append("LIMIT " + (pageNo - 1) * pageSize + "," + pageSize + " ");
        List<Map<String, Object>> applyList = sqlMapper.selectList(sql.toString());
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> map : applyList) {
            map.put("id", Integer.valueOf(map.get("id") + ""));
            map.put("productId", StringUtil.toString(map.get("productId")));// 产品ID
            map.put("productName", StringUtil.toString(map.get("productName")));// 公司名称
            map.put("productLogo", StringUtil.toString(map.get("productLogo")));// logo
            map.put("lendSpeed", StringUtil.toString(map.get("lendSpeed"))+"小时");//  放款速度
            map.put("dailyInterestRate", StringUtil.toString(map.get("dailyInterestRate")));// 日利息
            map.put("quato",
                    getQuato(StringUtil.toString(map.get("min_quato")), StringUtil.toString(map.get("max_quato"))));// 放款额度
            Integer minCycle=null;
            if(StringUtil.isNotEmpty(map.get("minCycle"))){
                minCycle=(int)map.get("minCycle");
            }
            map.put("cycle",
                    getCycle(minCycle, (int) map.get("max_cycle")) + "天");// 期限范围
            // 查询标签
            map.remove("min_cycle");
            map.remove("max_cycle");
            map.remove("min_quato");
            map.remove("max_quato");
            String label = platformService.getPlatformLabel(StringUtil.toString(map.get("productId")));
            map.put("label", label);// 标签
            result.add(map);
        }
        return result;
    }

    @Override
    public void insertApplyRecord(Long user, Long productId) {
        Long num = sqlMapper.selectOne("SELECT COUNT(1) AS num FROM customer_application_record WHERE borrower_id='"+user+"' AND product_id='"+productId+"' ", Long.class);
        if(num > 0){
            // 更新
            sqlMapper.update("UPDATE customer_application_record SET create_time=NOW(),update_time=NOW() WHERE borrower_id='"+user+"' AND product_id='"+productId+"' ");
        }else{
            sqlMapper.insert("INSERT INTO customer_application_record(borrower_id,product_id,create_time,update_time) VALUES('"+user+"','"+productId+"',NOW(),NOW()) ");
        }
    }

    @Override
    public Long Insert(CustomerBorrowInfo customerBorrowInfo) throws BusinessException {
        Integer rs=  mapper.insert(customerBorrowInfo);
        return rs>0?customerBorrowInfo.getId():null;
    }

    @Override
    public boolean DeleteByPk(Long aLong) throws BusinessException {
        return false;
    }

    @Override
    public boolean Update(CustomerBorrowInfo customerBorrowInfo) throws BusinessException {
        return false;
    }

    @Override
    public CustomerBorrowInfo selectByPk(Long aLong) throws BusinessException {
        return mapper.selectByPrimaryKey(aLong);
    }

    @Override
    public CustomerBorrowInfo selectByModel(CustomerBorrowInfoQuery customerBorrowInfoQuery) throws BusinessException {
        return null;
    }

    @Override
    public CustomerBorrowInfo selectBySelf(CustomerBorrowInfo customerBorrowInfo) throws BusinessException {
        return null;
    }

    @Override
    public List<CustomerBorrowInfo> selectListByModel(CustomerBorrowInfoQuery customerBorrowInfoQuery) throws BusinessException {
        return null;
    }

    @Override
    public Long selectCountByQueryMap(CustomerBorrowInfoQuery customerBorrowInfoQuery) {
        return null;
    }

    @Override
    public List<CustomerBorrowInfo> selectPageListByQueryMap(CustomerBorrowInfoQuery customerBorrowInfoQuery) throws BusinessException {
        return null;
    }
}